import 'package:lib_common/lib_common.dart';

class FocusWidget extends ConsumerStatefulWidget {
  /// 有焦点展示
  final Widget? focused;

  /// 无焦点展示
  final Widget? unfocused;

  /// 焦点实例
  final FocusNode? focusNode;

  /// 按压处理
  final VoidCallback? onTap;

  /// 获取焦点时监听
  final ValueChanged<FocusNode>? onFocusChange;

  /// 点击是否点击时自动获取焦点
  final bool autoFocus;

  /// 是否默认有焦点
  final bool defaultFocus;

  const FocusWidget({
    this.onTap,
    super.key,
    this.focusNode,
    this.autoFocus = false,
    this.defaultFocus = false,
    this.onFocusChange,
    this.focused,
    this.unfocused,
  });

  @override
  ConsumerState<ConsumerStatefulWidget> createState() {
    return _FocusWidgetState();
  }
}

class _FocusWidgetState extends ConsumerState<FocusWidget> {
  late FocusNode focusNode;

  final focusProvider = StateProvider<bool>((ref) => false);

  @override
  void initState() {
    super.initState();
    focusNode = widget.focusNode ?? FocusNode();
    focusNode.addListener(() {
      ref.refresh(focusProvider.notifier).state = focusNode.hasFocus;
      widget.onFocusChange?.call(focusNode);
    });
    if (widget.defaultFocus) {
      focusNode.requestFocus();
    }
  }

  @override
  void didUpdateWidget(covariant FocusWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.defaultFocus) {
      focusNode.requestFocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    var hasFocus = ref.watch(focusProvider.notifier).state;
    return InkWell(
        focusNode: focusNode,
        onTap: () {
          if (widget.autoFocus) {
            focusNode.requestFocus();
          }
          widget.onTap?.call();
        },
        child: hasFocus ? widget.focused : widget.unfocused);
  }

  @override
  void dispose() {
    focusNode.dispose();
    super.dispose();
  }
}
